package com.cdy.client.netty;

import com.cdy.common.command.PingCommand;
import io.netty.channel.*;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

import static com.cdy.client.netty.NettyClient.NETTY_CLIENT;


@ChannelHandler.Sharable
@Slf4j
public class ClientErrorHandler extends ChannelDuplexHandler {

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;
            if (e.state() == IdleState.WRITER_IDLE) {
                ctx.writeAndFlush(new PingCommand());
            }
        }
    }


    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        ctx.write(msg, promise.addListener((ChannelFutureListener) future -> {
            if (!future.isSuccess()) {
                log.error("send data to server exception occur: ", future.cause());
            }
        }));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error(cause.getMessage(), cause);
    }


    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channel.close();
        log.warn("与服务端断开连接,尝试进行重新连接");
        NettyClient client = channel.attr(NETTY_CLIENT).get();
        if (client != null && !client.getIsClose()) {
            client.reconnect();
        }
    }



}
